<template>
  <div class="w-full h-full overflow-y-auto overflow-x-hidden  border-t border-gray-200 pt-[20px]">
    <header class="flex items-center justify-between mb-[16px]">
      <div class="mb-[8px] text-[14px] text-[#333] font-medium">页签模块设置</div>
      <el-button :icon="Trash2" link @click="emit('delete')"></el-button>
    </header>
    <el-form>
      <!-- 背景设置 -->
      <div class="mb-[18px] border-b-[1px] border-[#E5E5E5]">
        <el-form-item :label="$t('competition.modules.tabs.backgroundSettings')">
          <el-color-picker v-model="model.bgColor" :style="`background-color: ${model.bgColor || '#000000'};`" />
        </el-form-item>
      </div>
      <!-- 页签管理 -->
      <el-form-item :label="$t('competition.modules.tabs.contentDetails')" label-position="top">
        <div class="w-full tabs-manager">
          <!-- 设置区标签栏（带滚动导航） -->
          <div class="tabs-bar">
            <!-- 左箭头 -->
            <button type="button" class="scroll-arrow left-arrow" :class="{ disabled: !canScrollLeft }"
              :disabled="!canScrollLeft" @click="scrollBy(-1)">‹</button>

            <!-- 可滚动的标签容器 -->
            <div ref="scrollRef" class="tabs-scroll" @scroll="updateArrows">
              <div v-for="(tab, i) in model.list" :key="tab.id" class="tab-item cursor-pointer"
                :class="{ active: i === model.active, editing: editingIndex === i }" @click="activate(i)">
                <template v-if="editingIndex === i">
                  <span :ref="(el: any) => setSizerRef(i, el)" class="input-sizer">{{ tab.title || '请输入' }}</span>
                  <el-input :ref="(el: any) => setEditRef(i, el)" v-model="tab.title"
                    :style="{ width: getEditWidth(i, tab.title) }" placeholder="请输入" @blur="stopEdit"
                    @keyup.enter="stopEdit" />
                </template>
                <template v-else>
                  <span @dblclick.stop="startEdit(i)"
                  class="text-[#0067d1]"
                    :class="i === model.active ? 'inline-block border-b-[2px] border-[#0067d1] text-left' : ''">{{
                      tab.title || getDefaultTitle(i) }}</span>
                </template>
                <i class="close" title="删除" @click.stop="removeTab(i)">×</i>
              </div>
            </div>

            <!-- 右箭头 -->
            <button type="button" class="scroll-arrow right-arrow" :class="{ disabled: !canScrollRight }"
              :disabled="!canScrollRight" @click="scrollBy(1)">›</button>

            <!-- 分隔线 -->
            <div class="divider"></div>

            <!-- 固定的添加按钮 -->
            <el-tooltip content="新增页签" placement="top">
              <el-button :icon="Plus" link @click="addTab"></el-button>
            </el-tooltip>
          </div>

          <!-- 富文本编辑器（针对当前激活的页签） -->
          <div v-if="model.list.length">
            <div v-for="(tab, index) in model.list" :key="tab.id" v-show="index === model.active">
              <WangEditor v-model="tab.content" mode="default" :scrollable="true" :height="470"
                class="w-full max-w-full" />
            </div>
          </div>
          <el-empty v-else :description="$t('competition.modules.tabs.addTabFirst')" />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { Trash2, Plus, X } from '@vben/icons'
import { $t } from '#/locales'
import WangEditor from '#/components/editor.vue'

export interface TabsState {
  bgColor: string
  textStyle: { size: number; bold: boolean }
  list: Array<{ id: number; title: string; content: string }>
  active: number
}

const model = defineModel<TabsState>({ required: true })
const emit = defineEmits<{ delete: [] }>()

const editingIndex = ref(-1)
const originalTitle = ref('')

// 滚动与编辑引用
const scrollRef = ref<HTMLDivElement | null>(null)
const canScrollLeft = ref(false)
const canScrollRight = ref(false)
// 为每个标签项的编辑输入维护独立 ref
const editRefs = ref<any[]>([])
function setEditRef(i: number, el: any) {
  if (el) editRefs.value[i] = el
  else delete editRefs.value[i]
}
// 用于自适应宽度的隐藏测量元素 refs
const sizerRefs = ref<HTMLElement[]>([])
function setSizerRef(i: number, el: HTMLElement | null) {
  if (el) sizerRefs.value[i] = el
  else delete sizerRefs.value[i]
}
function getEditWidth(i: number, txt?: string) {
  const sizer = sizerRefs.value[i]
  if (!sizer) return '64px'
  // 使用 sizer 的实际宽度 + 16px 边距，最小 64px，最大 240px（防溢出）
  const text = (txt ?? '').trim() || '请输入'
  sizer.textContent = text
  const w = Math.ceil(sizer.offsetWidth) + 16
  return Math.min(Math.max(w, 64), 240) + 'px'
}


function getDefaultTitle(i: number) {
  const zh = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
  return `标题${zh[i] ?? i + 1}`
}

onMounted(() => {
  // 初始化时确保至少两个默认页签
  if (!model.value.list || model.value.list.length === 0) {
    model.value.list = [
      { id: Date.now(), title: '标题一', content: '' },
      { id: Date.now() + 1, title: '标题二', content: '' },
    ]
    model.value.active = 0
  }
  nextTick(updateArrows)
})

function updateArrows() {
  const el = scrollRef.value
  if (!el) {
    canScrollLeft.value = false
    canScrollRight.value = false
    return
  }
  const maxScrollLeft = el.scrollWidth - el.clientWidth
  canScrollLeft.value = el.scrollLeft > 0
  canScrollRight.value = el.scrollLeft < maxScrollLeft - 1
}

function ensureVisible(index: number) {
  const el = scrollRef.value
  if (!el) return
  const items = el.querySelectorAll<HTMLElement>('.tab-item')
  const target = items[index]
  if (!target) return
  const padding = 20
  const left = target.offsetLeft - padding
  const right = target.offsetLeft + target.offsetWidth + padding
  const viewLeft = el.scrollLeft
  const viewRight = viewLeft + el.clientWidth
  if (left < viewLeft) el.scrollTo({ left: Math.max(left, 0), behavior: 'smooth' })
  else if (right > viewRight) el.scrollTo({ left: right - el.clientWidth, behavior: 'smooth' })
  setTimeout(updateArrows, 200)
}

function scrollBy(dir: number) {
  const el = scrollRef.value
  if (!el) return
  const delta = Math.floor(el.clientWidth * 0.6) * dir
  el.scrollBy({ left: delta, behavior: 'smooth' })
  setTimeout(updateArrows, 200)
}
// 当外部（预览区域）更新了 active 时，滚动到对应标签
watch(() => model.value.active, (newIndex) => {
  nextTick(() => ensureVisible(newIndex))
})

function addTab() {
  const idx = model.value.list.length + 1
  model.value.list.push({ id: Date.now(), title: $t(`competition.homePage.defaultData.tabTitle`) + idx as string, content: '' })
  model.value.active = model.value.list.length - 1
  nextTick(() => {
    ensureVisible(model.value.active)
  })
}
function removeTab(i: number) {
  if (i < 0 || i >= model.value.list.length) return
  model.value.list.splice(i, 1)
  if (!model.value.list.length) {
    model.value.active = 0
    editingIndex.value = -1
    nextTick(updateArrows)
    return
  }
  if (model.value.active >= model.value.list.length) model.value.active = model.value.list.length - 1
  nextTick(() => ensureVisible(model.value.active))
}

function activate(i: number) {
  model.value.active = i
  nextTick(() => ensureVisible(i))
}
function startEdit(i: number) {
  editingIndex.value = i
  // 保存原始标题
  originalTitle.value = model.value.list[i]?.title || ''
  nextTick(() => {
    const input = editRefs.value[i] as any
    try { input?.focus?.() } catch { }
  })
}
function stopEdit() {
  // 检查当前编辑的标签是否存在且标题为空
  if (editingIndex.value >= 0 && editingIndex.value < model.value.list.length) {
    const currentTab = model.value.list[editingIndex.value]
    if (currentTab && (!currentTab.title || currentTab.title.trim() === '')) {
      // 如果标题为空，恢复原始标题
      currentTab.title = originalTitle.value
    }
  }
  editingIndex.value = -1
  originalTitle.value = ''
}
</script>

<style scoped>
.tabs-manager .tabs-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

/* 滚动区域与箭头/加号布局 */
.tabs-manager .tabs-scroll {
  flex: 1;
  display: flex;
  align-items: center;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none;
}

.tabs-manager .tabs-scroll::-webkit-scrollbar {
  display: none;
}

.tabs-manager .scroll-arrow {
  border: none;
  background: transparent;
  color: #666;
  font-size: 16px;
  line-height: 1;
  padding: 6px 4px;
  cursor: pointer;
}

.tabs-manager .scroll-arrow.disabled {
  opacity: .4;
  cursor: not-allowed;
}

.tabs-manager .divider {
  width: 1px;
  height: 16px;
  background: #E5E6EB;
  margin: 0 6px;
}

/* 隐藏测量文本元素，用于计算 input 宽度 */
.tabs-manager .input-sizer {
  position: absolute;
  visibility: hidden;
  white-space: pre;
  font-size: 14px;
  font-weight: 400;
}

.tabs-manager .tab-add-btn:hover {
  background: #f5f7ff;
}

/* 标签项样式 */
.tabs-manager .tab-item {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  color: #333;
  font-size: 14px;
  white-space: nowrap;
  position: relative;
}

.tabs-manager .tab-item :deep(.el-input__wrapper) {
  box-shadow: none;
  border: none;
  border-bottom: 2px solid #0067d1;
  border-radius: 0;
  padding: 0;
  height: 26px;
}
/* 关闭按钮（灰色圆形） */
.tabs-manager .tab-item .close {
  margin-left: 8px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #aeaeae;
  color: #fff;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-style: normal;
  padding-bottom: 5px;
  /* line-height: 30px; */
  font-size: 20px;
  font-weight: 300;
}
:deep(.wang-editor-container) {
  border-radius: 4px;
  max-width: 100%;
  overflow: hidden;
}

:deep(.w-e-toolbar) {
  border-bottom: 1px solid #dcdfe6;
}

:deep(.w-e-bar-item) {
  button {
    padding: 3px !important;
  }
}
</style>
